package com.example.expresshelp.service;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.example.expresshelp.bean.Address;
import com.example.expresshelp.bean.City;
import com.example.expresshelp.bean.District;
import com.example.expresshelp.bean.District;
import com.example.expresshelp.bean.Province;
import com.example.expresshelp.bean.Towntr;
import com.example.expresshelp.db.MySqliteHelper;
import com.example.expresshelp.util.Constance;
import com.example.expresshelp.util.HttpClientHelper;
import com.example.expresshelp.util.Validator;

/**
 * 区
 * 
 * @author josan_tang
 * 
 */
public class DistrictService {
	private static final String TAG = "DistrictService";

	/**
	 * 解析信息
	 * 
	 */
	public static List<District> parseDistrict(Context context, String pCode,
			String cid, String cCode, String districtHtml) {
		List<District> districtList = new ArrayList<District>();
		String resultHtml = HttpClientHelper.doPost(districtHtml, null, 0);
		if (!Validator.isEffective(resultHtml)) {
			return null;
		}
		Document document = Jsoup.parse(resultHtml);
		Elements districtRows = document.getElementsByClass("countytr");

		for (int i = 0; i < districtRows.size(); i++) {
			District district = new District();
			Element tr = districtRows.get(i);
			Elements tds = tr.getElementsByTag("td");
			// 第一个td里是超链接没和城市代码
			Element codeTd = tds.get(0);
			Element nameTd = tds.get(1);
			Elements aCodeS = codeTd.getElementsByTag("a");
			String dCode = "";
			String dName = "";
			if (aCodeS != null && aCodeS.size() > 0) { //
				Element codeA = aCodeS.get(0);
				String hrefHtml = codeA.attr("href");
				String allCode = codeA.text();
				// 110101中的最后一个01
				dCode = allCode.substring(4, 6);
				// 名称
				Element nameA = nameTd.getElementsByTag("a").get(0);
				dName = nameA.text();
				long did = saveToDB(context, cid, dCode, dName);
				district.setId(did + "");
				// 只有可点击的时候，才能往下遍历
				String towntrUrl = Constance.BASE_URL + pCode + "/" + hrefHtml;
				List<Towntr> towntrList = TowntrService.parseTowntr(context,
						pCode, cCode, did + "", dCode, towntrUrl);
				district.setTowntrList(towntrList);
			} else { // 没有a标签，证明没有下级元素
				String allCode = codeTd.text();
				dCode = allCode.substring(4, 6);
				dName = nameTd.text();
				long did = saveToDB(context, cid, dCode, dName);
				district.setId(did + "");
			}
			Log.i("express", "districtName - >" + dCode + dName);

			district.setCid(cid);
			district.setCityCode(dCode);
			district.setCode(dCode);
			district.setName(dName);
			districtList.add(district);
		}
		return districtList;

	}

	/**
	 * 把信息保存到数据库中
	 * 
	 * @param context
	 * @param code
	 * @param name
	 */
	public static long saveToDB(Context context, String provinceCode,
			String DistrictCode, String DistrictName) {
		try {
			// 构造参数
			ContentValues values = new ContentValues();
			values.put("ccode", provinceCode);
			values.put("code", DistrictCode);
			values.put("name", DistrictName);
			return MySqliteHelper.getInstance(context).insert(
					Constance.DISTRICT_TABLE_NMAE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<District> getDistrictByCitycode(Context context,
			String cityCode) {
		List<District> list = null;
		String where = " ccode=" + cityCode;
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.DISTRICT_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<District>();
			while (cursor.moveToNext()) {
				District district = new District();
				district.setCityCode(cityCode);
				String code = cursor.getString(cursor.getColumnIndex("code"));
				district.setCode(code);
				List<Towntr> towntrList = TowntrService
						.getTowntrByDistrictcode(context, code);
				district.setTowntrList(towntrList);
				district.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(district);
			}
		}
		return list;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static District find(Context context, String did) {
		District district = null;
		String where = " id='" + did + "'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.DISTRICT_TABLE_NMAE, where);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				district = new District();
				district.setId(cursor.getString(cursor.getColumnIndex("id")));
				district.setCid(cursor.getString(cursor.getColumnIndex("ccode")));
				district.setCode(cursor.getString(cursor.getColumnIndex("code")));
				district.setName(cursor.getString(cursor.getColumnIndex("name")));
			}
		}
		return district;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<Address> getDistrictByName(Context context, String name) {
		List<Address> addressList = null;
		List<District> list = null;
		String where = " name like '%" + name + "%'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.DISTRICT_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<District>();
			addressList = new ArrayList<Address>();
			while (cursor.moveToNext()) {
				District district = new District();
				Address address = new Address();

				
				String ccode = cursor.getString(cursor.getColumnIndex("ccode"));
				district.setCid(ccode);
				district.setCode(cursor.getString(cursor.getColumnIndex("code")));
				district.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(district);
				address.setFilterAddress(district.getName());
				City city = CityService.find(context, district.getCid());
				StringBuffer totalAddress = new StringBuffer();
				if (city != null) {
					String cityName = city.getName();
					if (!(cityName.equals("市辖区") || cityName.equals("县"))) {
						totalAddress.append(",");
						totalAddress.append(city.getName());
					}
					Province province = ProvinceService.find(context,
							city.getPid());
					if (province != null) {
						totalAddress.append(",");
						totalAddress.append(province.getName());
					}
				}
				address.setUnfilterAddress(totalAddress.toString());
				addressList.add(address);
			}
		}
		return addressList;
	}
}
